//
//  VideoItem.m
//  VidCrusher
//
//  Created by Cemil Browne on 4/06/08.
//  Copyright 2008 Cemil Browne. All rights reserved.
//
/*
 This program is free software: you can redistribute it and/or modify
 it under the terms of the GNU General Public License as published by
 the Free Software Foundation, either version 3 of the License, or
 (at your option) any later version.
 
 This program is distributed in the hope that it will be useful,
 but WITHOUT ANY WARRANTY; without even the implied warranty of
 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 GNU General Public License for more details.
 
 You should have received a copy of the GNU General Public License
 along with this program.  If not, see <http://www.gnu.org/licenses/>.
 */ 

#import "VideoItem.h"
#import <QuickTime/QuickTime.h>
#import <QTKit/QTKit.h>
#import "UKDockProgressIndicator.h"

@implementation VideoItem


// standard init. 
-(id) init
{
	[super init];
	[self setFileName:@"None"];
	[self setPath:@"none"];
	[self setCompressAvailable:YES];
	return self;
}

// This is what is called externally.  Load aFilename. 
- (id) initWithFileName:(NSString *) aFileName
{
	[self init];
	
	// The file has already been verified as existing at this point. we need to load & set attributed. 
	NSFileManager *myFM = [NSFileManager defaultManager];
	[self setFileSize:[self stringFromFileSize:[[[myFM fileAttributesAtPath:aFileName traverseLink:NO] objectForKey:@"NSFileSize"] longValue]] ]; 
	[self setPath:aFileName];
	[self setFileName:[aFileName lastPathComponent]];
	if(![self setMovie])
	{
		return nil;  // If the movie couldn't be opened.  
	}
	[self setVideoType:1];
	[self setShowName:@""];
	[self setSeasonNumber:@""];
	[self setEpisodeNumber:@""];
	[self checkForTVShow]; // Parse the filename for TV Show information. 
	return self;
}

// Attempt to open the movie.  If it opens, grab its attributes. 
- (BOOL)setMovie
{
	if([QTMovie canInitWithFile:path])
	{
		NSError *movieError = nil;
		movie = [[QTMovie alloc] initWithFile:path error:&movieError]; // Open it. 
		
		if(movieError)
		{
			NSRunAlertPanel(@"File could not be opened", [movieError localizedDescription], @"OK", nil, nil);
			NSLog([movieError localizedDescription]);
			return NO;
		}
		// Grab the duration
		QTTime duration = [[movie attributeForKey:@"QTMovieDurationAttribute"] QTTimeValue];
		length = round(duration.timeValue/duration.timeScale);
		
		if(length == 0)
		{
			
			NSRunAlertPanel(@"File could not be opened.", [NSString stringWithFormat:@"%@ does not appear to be a valid movie file.", [self fileName]], @"OK", nil, nil);
			return NO;
		}
		[self setPosterFrame:[movie posterImage]];
		return YES;
	}
	else
	{
		NSRunAlertPanel(@"File could not be opened", [NSString stringWithFormat:@"%@ does not appear to be a valid movie file. If QuickTime can't open it, neither can I.", [self fileName]], @"OK", nil, nil);
		NSLog(@"Invalid file passed in.");
		return NO;
	}
	
}
- (QTMovie *)movie
{
	return [[movie retain] autorelease];
}

// This function uses regexes to check whether or not the file is a TV Show.  If so, it tries to parse the relevant data from it. 
- (void) checkForTVShow
{
	if([fileName isMatchedByRegex:@"[sS]\\d{1,3}[eE]\\d{1,3}"])
	{
		NSRange range = [fileName rangeOfRegex:@"[sS]\\d{1,3}[eE]\\d{1,3}"];
		NSRange beginning;
		beginning.location = 0;
		beginning.length = range.location;
		NSRange season = [fileName rangeOfRegex:@"[sS]\\d{1,3}" inRange:range];
		season.location++;
		season.length--;
		NSRange episode= [fileName rangeOfRegex:@"[eE]\\d{1,3}" inRange:range];
		episode.location++;
		episode.length--;
		[self setVideoType:0];
		[self setSeasonNumber:[NSString stringWithFormat:@"%d", [[fileName substringWithRange:season] intValue]]];
		[self setEpisodeNumber:[NSString stringWithFormat:@"%d", [[fileName substringWithRange:episode] intValue]]];
		[self setShowName:[[[fileName substringWithRange:beginning] componentsSeparatedByString:@"."] componentsJoinedByString:@" "]];
	}
	else if([fileName isMatchedByRegex:@"^\\d{3,4}"])
	{
		NSRange range = [fileName rangeOfRegex:@"^\\d{3,4}"];
		NSRange tempSeason;
		tempSeason.location = 0;
		NSRange tempEp;
		if(range.length == 4)
		{
			tempSeason.length = 2;
			tempEp.location = 2;
			tempEp.length = 2;
		}
		if(range.length == 3)
		{
			tempSeason.length = 1;
		}
		else
		{
			return;
		}
		tempEp.location = tempSeason.length;
		tempEp.length = 2;
		[self setVideoType:0];
		[self setSeasonNumber:[NSString stringWithFormat:@"%d", [[fileName substringWithRange:tempSeason] intValue]]];
		[self setEpisodeNumber:[NSString stringWithFormat:@"%d", [[fileName substringWithRange:tempEp] intValue]]];
	}
}

- (BOOL)CompressAvailable
{
	return YES;
}
- (void)setCompressAvailable:(BOOL)isAvail
{
	CompressAvailable = YES;
}
- (NSString *)fileName
{
	
	return fileName;
}
- (void)setFileName:(NSString *) aString
{
	fileName = [aString copy];
}
- (NSString *)path
{
	return path;
}
- (void)setPath:(NSString *) aPath
{
	path = [aPath copy];
}
- (NSString *)fileSize
{
	return fileSize;
}
- (void)setFileSize:(NSString *) aSize
{
	fileSize = [aSize copy];
}
- (NSInteger )videoType
{
	return videoType;
}
- (void)setVideoType:(NSInteger)aVideoType
{
	videoType = aVideoType;
}
- (NSString *)showName
{
	return showName;
}
- (void)setShowName:(NSString *)aShowName
{
	showName = [aShowName copy];
}
- (NSString *)seasonNumber
{
	return seasonNumber;
}
- (void)setSeasonNumber:(NSString *)aSeasonNumber
{
	seasonNumber = [aSeasonNumber copy];
}
- (NSString *)episodeNumber
{
	return episodeNumber;
}
- (void)setEpisodeNumber:(NSString *)anEpisodeNumber
{
	episodeNumber = [anEpisodeNumber copy];
}

// Converts long to human readable file size.
- (NSString *)stringFromFileSize:(long)theSize
{
	float floatSize = theSize;
	if (theSize<1023)
		return([NSString stringWithFormat:@"%i bytes",theSize]);
	floatSize = floatSize / 1024;
	if (floatSize<1023)
		return([NSString stringWithFormat:@"%1.1f KB",floatSize]);
	floatSize = floatSize / 1024;
	if (floatSize<1023)
		return([NSString stringWithFormat:@"%1.1f MB",floatSize]);
	floatSize = floatSize / 1024;
	
	// Add as many as you like
	
	return([NSString stringWithFormat:@"%1.1f GB",floatSize]);
}

// converts length in to human readable time. 
- (NSString *) length
{
	int mins = length/60;
	int secs = length % 60;
	return [NSString stringWithFormat:@"%d:%02d", mins, secs];
}
- (void) setLength:(int) aLength
{
	length = aLength;
}
- (NSImage *)posterFrame
{
	return posterFrame;
}

// Set poster frame, but resize it down to 40 pixels high.  
- (void) setPosterFrame: (NSImage *) aPosterFrame
{
	NSSize temp = [aPosterFrame size];
	float ratio = temp.width/temp.height;
	temp.height = 40;
	temp.width = 40*ratio;
	posterFrame = [aPosterFrame copy];
	[posterFrame setSize:temp];
}
@end
